package com.liao.badminton.filter;

import com.github.pagehelper.PageHelper;
import com.liao.badminton.code.ProjectException;
import com.liao.badminton.code.ResponseRest;
import com.liao.badminton.code.util.ResponseUtils;
import com.liao.badminton.context.BaseContextHandler;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MyFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request, response);
            BaseContextHandler.remove();
            //可以清除分布插件的缓存
            PageHelper.clearPage();
        } catch (ProjectException e) {
            String requestURI = request.getRequestURI();
            ResponseUtils.out(response, ResponseRest.fail(requestURI).setCode(e.getCode()).setMsg(e.getMessage()));
        } catch (Exception e) {
            logger.error("系统异常", e);
            String requestURI = request.getRequestURI();
            ResponseUtils.out(response, ResponseRest.fail(requestURI));


        }
    }
}
